"""
①先查询数据
②将查询的数据 填充到 html中
③我们把最新的 赫塔缪勒文件放到指定的目录中
"""
import time
import os
from goods.models import GoodsChannel
from .models import ContentCategory
from collections import OrderedDict
from django.template import loader
from django.conf import settings

def generate_static_index_html():
    """
    生成静态的主页html
    :return:
    """
    print('%s:generate_static_index' % time.ctime())

    # 初始化存储容器
    categories = OrderedDict()

    # 获取一级分类
    channels = GoodsChannel.objects.order_by('group_id','spquence')

    # 对一级分类进行遍历
    for channel in channels:
        #获取group_id
        group_id = channel.group_id
        #判断group_id 是否在存储容器，如果不在就初始化
        if group_id not in categories:
            categories[group_id] = {
                'channels':[],
                'sub_cats':[]
            }

        one = channel.category

        #为channels填充数据
        categories[group_id]['channels'].append({
            'id':one.id,
            'name':one.name,
            'url':channel.url
        })

        #为sub_cats填充数据
        for two in one.goodscategory_set.all():
            #初始化容器
            two.sub_cats = []
            #遍历获取
            for three in two.goodscategory_set.all():
                two.sub_cats.append(three)

            #组织数据
            categories[group_id]['sub_cats'].append(two)

    # 广告和首页数据
    contents = {}
    content_categories = ContentCategory.objects.all()

    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    context = {
        'categories':categories,
        'contents':contents
    }


    #1、先获取模板
    #get_template 到系统的指令的模板目录中加载指定的模板
    template = loader.get_template('index.html')

    #2、将获取的最新数据传递给模板，让模板进行渲染，会把渲染号的html返回
    html_data = template.render(context)

    #3、把我们的html内容 写入到指定的目录
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR,'index.html')

    #4、写入
    with open(file_path,'w') as f:
        f.write(html_data)





























































